package _5thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: wang zhen
 * @create: 2022-06-10 11:47
 */
public class CompletableFutureTest {

    public static void main(String[] args) throws Exception {

        test3();
    }


    public static void test1() throws Exception{
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "启动");

        },threadPool);



        System.out.println("结果:"+future1.get());


        threadPool.shutdown();
    }

    public static void test2() throws Exception{
        ExecutorService threadPool = Executors.newFixedThreadPool(3);


        CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + "启动");
            return 2;

        },threadPool).whenComplete((v,e) ->{
            System.out.println("结果:"+v);

            System.out.println("异常:"+e);
        });


        System.out.println(Thread.currentThread().getName() + "运行");
        threadPool.shutdown();
    }


    public static void test3() throws Exception{
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + "启动");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;

        },threadPool).whenComplete((v, e) -> {
            System.out.println("结果:" + v);

            System.out.println("异常:" + e);
        });

        Integer integer = future.get();

        System.out.println("最终结果:"+integer);
        threadPool.shutdown();
    }

}
